// routes/chart.js
import express from "express";
import User from "../models/User.js";
import verifyToken from "../middlewares/verifyToken.js";

const router = express.Router();

router.get("/protected-data", verifyToken, (req, res) => {
  res.json({ code: 0, msg: "成功", data: "这是受保护的数据", user: req.user });
});

// 活跃用户数
router.get("/active-users", verifyToken, async (req, res) => {
  const count = await User.countDocuments({ isActive: true });
  res.json({ code: 0, data: { activeUsers: count } });
});

// 用户注册趋势（过去7天）
router.get("/register-trend", async (req, res) => {
  const result = [];
  for (let i = 6; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    const next = new Date(date);
    next.setDate(next.getDate() + 1);
    const count = await User.countDocuments({
      createdAt: { $gte: date, $lt: next },
    });
    result.push({ day: `周${7 - i}`, value: count });
  }
  res.json({ code: 0, data: result });
});

// 用户分布
router.get("/user-distribution", async (req, res) => {
  const genderAgg = await User.aggregate([
    { $group: { _id: "$gender", total: { $sum: 1 } } },
  ]);
  const regionAgg = await User.aggregate([
    { $group: { _id: "$region", total: { $sum: 1 } } },
  ]);
  res.json({
    code: 0,
    data: {
      gender: genderAgg.map((g) => ({ name: g._id, value: g.total })),
      region: regionAgg.map((r) => ({ name: r._id, value: r.total })),
    },
  });
});

// 访问热力图
router.get("/user-map", async (req, res) => {
  try {
    const regionAgg = await User.aggregate([
      { $group: { _id: "$region", total: { $sum: 1 } } },
    ]);
    const regionData = regionAgg.map((r) => ({
      name: r._id,
      value: r.total,
    }));
    res.json({
      code: 0,
      data: regionData,
    });
  } catch (err) {
    console.error("❌ 地区聚合错误", err);
    res.json({ code: 1, msg: "获取地区数据失败" });
  }
});

router.get("/system-status", (req, res) => {
  const data = [
    { name: "CPU", value: Math.floor(Math.random() * 100) },
    { name: "内存", value: Math.floor(Math.random() * 100) },
    { name: "磁盘", value: Math.floor(Math.random() * 100) },
  ];
  res.json({
    code: 0,
    data,
  });
});

router.get("/activity-rank", (req, res) => {
  const activityNames = [
    "开学典礼",
    "春季团建",
    "安全演练",
    "招聘宣讲",
    "编程大赛",
    "元宵活动",
  ];
  const data = activityNames
    .map((name) => ({
      name,
      value: Math.floor(Math.random() * 5000 + 500),
    }))
    .sort((a, b) => b.value - a.value);
  res.json({
    code: 0,
    data,
  });
});

// ES Module 写法必须 export default
export default router;
